package com.itheima.web.servlet;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    private UserService us = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   /*     request.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        if ("findAll".equals(method)) {
            findAll(request, response);
        } else if ("add".equals(method)) {
            add(request, response);
        } else if ("ById".equals(method)) {
            ById(request, response);
        } else if ("update".equals(method)) {
            update(request, response);
        } else if ("delete".equals(method)) {
            delete(request, response);
        }*/

        try {
            //0. 设置请求编码, 编码处理一定要设置在获取参数之前
            request.setCharacterEncoding("UTF-8");

            //1. 获取method参数
            String methodName = request.getParameter("method");

            //2. 基于反射动态调用类的方法
            //2.1 获取当前类的Class字节码对象
            Class clazz = this.getClass();
            //2.2 获取方法对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this, request, response);  // this.update(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //删除用户
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        us.delete(id);
        response.sendRedirect(request.getContextPath() + "/userServlet?method=findAll");

    }

    //修改用户
    public void update(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);//封装对象

            us.update(user);
            response.sendRedirect(request.getContextPath() + "/userServlet?method=findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //回显数据
    public void ById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        User user = us.ById(id);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/update.jsp").forward(request, response);
    }

    //添加用户
    public void add(HttpServletRequest request, HttpServletResponse response) {
        //获取表单内容
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);//封装对象

            us.add(user);
            response.sendRedirect(request.getContextPath() + "/userServlet?method=findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询用户
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users = us.findAll();
        request.setAttribute("users", users);
        findByPage(request,response);
       // request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
    //登录
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //先判断验证码是否正确
        String checkCode = request.getParameter("checkCode");
        System.out.println(checkCode);
        //获取程序生成放在session中的验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //删除session中的验证码,确保每次验证码都是一次性的
        session.removeAttribute("CHECKCODE_SERVER");

        //判断两个验证码是否一致
        if(!checkCode.equalsIgnoreCase(checkcode_server)){
            //不一样
            request.setAttribute("msg","验证码有误");
            //转发到登陆页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        //验证码正确就比较用户名跟密码是否一致
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if("jack".equals(username)&&"1234".equals(password)){
            request.getSession().setAttribute("username",username);
            /*String rememberName = request.getParameter("rememberName");
            if("yes".equals(rememberName)){
                //通过cookie存储用户名
                Cookie cookie=new Cookie("rememberName",username);
                cookie.setMaxAge(24*60*60);
                response.addCookie(cookie);
            }*/

            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return;
        }

        request.setAttribute("msg","用户名或密码有误!");
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }

    //删除选中
    public void deleteSelected(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] uids = request.getParameterValues("uid");
        us.deleteSelected(uids);
        response.sendRedirect(request.getContextPath() + "/userServlet?method=findAll");
    }
    //分页查询
    public void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");

        PageInfo page = us.findByPage(currentPageStr,pageSizeStr);
        System.out.println(page);
        request.setAttribute("page",page);
        request.getRequestDispatcher("/list.jsp").forward(request,response);

    }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
